import {
  OnInit, Component, ViewChild, AfterViewInit, ElementRef, ChangeDetectionStrategy,
  ViewEncapsulation, Output, Input, OnChanges, SimpleChanges, EventEmitter
} from '@angular/core';
import BScroll from '@better-scroll/core';
import ScrollBar from '@better-scroll/scroll-bar';
import MouseWheel from '@better-scroll/mouse-wheel'
import { Song } from 'src/app/routes/entity';
import { timer } from 'rxjs';
BScroll.use(ScrollBar);
BScroll.use(MouseWheel);

@Component({
  selector: 'app-panel-scroll',
  template: `
    <div class="panel-scroll" #wrapper>
      <ng-content></ng-content>
    </div>
  `,
  styles: [`.panel-scroll{width: 100%; height: 100%; overflow: hidden;}`],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class PanelScrollComponent implements OnInit, AfterViewInit, OnChanges {

  private betterScroll: BScroll;

  @Input()
  private refreshDelay = 50;

  @Input()
  private data: Song[];

  @Output()
  onScrollEnd: EventEmitter<number> = new EventEmitter<number>()

  @ViewChild('wrapper', { static: true })
  private wrapperRef: ElementRef;

  constructor(readonly el: ElementRef) { }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['data']) {
      this.resfreshPanelScroll();
    }
  }

  ngAfterViewInit(): void {
    this.betterScroll = new BScroll(this.wrapperRef.nativeElement, {
      scrollbar: { interactive: true },
      mouseWheel: {}
    });

    this.betterScroll.on('scrollEnd', ({ y }) => this.onScrollEnd.emit(y));
  }

  scrollToElement(...args): void {
    this.betterScroll.scrollToElement.apply(this.betterScroll, args);
  }

  scrollTo(...args): void {
    this.betterScroll.scrollTo.apply(this.betterScroll, args);
  }

  resfreshPanelScroll(): void {
    timer(this.refreshDelay).subscribe(() => {
      this.betterScroll.refresh();
    });
  }

}